<?php


namespace app\sub\controller;


use TencentCloud\Scf\V20180416\Models\Code;
use think\Db;
use think\facade\Config;

class Goods extends \Common
{

    private $spec = ["size" => "规格"];

    # 获取商品列表
    public function GetGoods()
    {
        $aid = isset($this->token["pid"]) ? $this->token["pid"] : $this->token["id"];
        $admin = Db::name("admin")->where("aid", $aid)->find();
        if (!isset($_GET["limit"]) && $_GET["send_user"] == "" && $_GET["buy_user"] == "") {
            Code(200, false, ["list" => [], "lot_name" => "", "total" => 0]);
        }
            $whereArr = [];

            if (isset($_GET["search"]) && $_GET["search"] != "") {
                $whereArr[] = "(number = '{$_GET["search"]}' or name like '%{$_GET["search"]}%')";
            }

            $checkAdmin = Db::name("admin")->where("aid", $this->token["id"])->find();
            if ($checkAdmin["roles"] == 4) {
                $whereArr[] = "(state = 8)";
            }

            if (isset($_GET["buy_user"]) && $_GET["buy_user"] != "") {
                $arr = explode("Co-", $_GET["buy_user"]);
                if (count($arr) > 1) {
                    $id = $arr[1];
                    $whereArr[] = "up_id = {$id}";
                } else {
                    $id = $_GET["buy_user"];
                    $whereArr[] = "ub_id = {$id}";
                }
                if ($admin["roles"] == 3) { # 会计 查询未在订单的和未付款的
                    $whereArr[] = "(state = 3 or state = 9)";
                    $whereArr[] = "b_oid = 0";
                } else if ($admin["roles"] == 2) { # 提货 查询在订单的和提货或者提完货的
                    $whereArr[] = "(state = 4 or state = 3)";
                    $whereArr[] = "b_oid != 0";
                } else if ($admin["roles"] == 4) { # 审核 查询在订单的待审核
                    $whereArr[] = "(state = 8)";
                    $whereArr[] = "b_oid != 0";
                }
            }
            if (isset($_GET["send_user"]) && $_GET["send_user"] != "") {
                $whereArr[] = "us_id = {$_GET["send_user"]}";
                if ($admin["roles"] == 3) { # 会计 查询未在订单的和未付款的
                    $whereArr[] = "(state = 4 or state = 5 or state = 6 or state = 9)";
                    $whereArr[] = "s_oid = 0";
                }
            }

            $where = join(" and ", $whereArr);
            if (isset($_GET["limit"]) && $_GET["limit"] != "") {
                $page = $_GET["page"];
                $limit = $_GET["limit"];
//                $good = Db::name("goods")->where($where)->orderRaw("field(state, 1, 7, 5, 4, 3, 6 ,0 ,-1), clinch_time desc")->page($page, $limit)->select();
                $good = Db::name("goods")->where($where)->orderRaw("gid desc,number asc")->page($page, $limit)->select();
                $count = Db::name("goods")->where($where)->count();
            } else {
//                $good = Db::name("goods")->where($where)->orderRaw("field(state, 1, 7, 5, 4, 3, 6 ,0 ,-1), clinch_time desc")->select();
                $good = Db::name("goods")->where($where)->orderRaw("gid desc,number asc")->select();
                $count = Db::name("goods")->where($where)->count();
            }

            $list = [];
            if (!empty($good)) {
                foreach ($good as $value) {
                    $buyNumber = '';
                    $SendUser = Db::name("user_send")->where("us_id", $value["us_id"])->find();
                    if ($value["up_id"] == 0) {
                        $BuyUser = Db::name("user_buy")->where("ub_id", $value["ub_id"])->find();
                        if (!empty($BuyUser)) {
                            $number = Db::name("num")->where("nid", $value["nid"])->find();
                            if (!empty($number)) {
                                $buyNumber = $number["number"];
                            }
                        }
                    } else {
                        $BuyUser = Db::name("user_proxy")->where("up_id", $value["up_id"])->find();
                    }
                    $list[] = [
                        "id" => $value["gid"],
                        "is_break" => (int)$value["is_break"],
                        "state" => (isset($_GET["buy_user"]) && $_GET["buy_user"] != "") ? $value["state"] == 7 ? 5 : (int)$value["state"] : (int)$value["state"],
                        "eval_price" => eval_price($value, 2),
                        "final_price" => (float)$value["final_price"],
                        "name" => $value["name"],
                        "number" => $value["number"],
                        "start_price" => (float)$value["price"],
                        "resr_price" => (float)$value["resr_price"],
                        "buy_user" => empty($BuyUser) ? "未知" : $BuyUser["name"],
                        "buy_num" => $buyNumber,
                        "send_user" => empty($SendUser) ? "未知" : $SendUser["name"],
                        "spec" => spec($value),
                        "year" => $value["year"],
                        "remark" => $value["remark"],
                        "location" => $value["location"],
                        "postage" => (float)$value["postage"],
                        "is_company" => $value["up_id"] != 0,
                        "id_number" => $value["id_number"],
                        "indepot_date" => $value["indepot_date"],
                        "outdepot_date" => $value["outdepot_date"],
                        "track_number" => $value["track_number"],
                        "is_settlement" => $value["is_settlement"],
                        "introduction" => $value["introduction"],
                        "keyword" => $value["keyword"],
                        "link" => $value["link"],
                    ];
                }
            }
            Code(200, false, ["list" => $list, "lot_name" => '', "total" => $count]);

    }

    public function GetGoodsDetail()
    {
        if (isset($_GET["id"])) {
            $id = $_GET["id"];
            $good = Db::name("goods")->where("gid", $id)->find();
            $img = $this->SearchImg($good["lid"], $good["number"], false, false, true);
            $append_img = $this->SearchImgAppend($good["lid"], $good["number"]);
            $data = [
                "id" => (int)$good["gid"],
                "us_id" => $good["us_id"] == 0 ? "" : (int)$good["us_id"],
                "lid" => (int)$good["lid"],
                "img" => $img,
                "level" => $good["level"],
                "lib_number" => $good["lib_number"],
                "name" => $good["name"],
                "number" => $good["number"],
                "recommend" => $good["recommend"],
                "remark" => $good["remark"],
                "report" => $good["report"],
                "resr_price" => (float)$good["resr_price"],
                "start" => (float)$good["price"],
                "end_price" => (float)$good["end_price"],
                "begin_price" => (float)$good["begin_price"],
                "size" => $good["size"],
                "style" => $good["style"],
                "summary" => $good["summary"],
                "year" => $good["year"],
                "classname" => $good["classname"],
                "author" => $good["author"],
                "appendix" => $good["appendix"],
                "append_img" => $append_img,
                "location" => $good["location"],
                "postage" => $good["postage"],
                "id_number" => $good["id_number"],
                "indepot_date" => $good["indepot_date"],
                "outdepot_date" => $good["outdepot_date"],
                "track_number" => $good["track_number"],
                "is_settlement" => $good["is_settlement"],
                "introduction" => $good["introduction"],
                "keyword" => $good["keyword"],
                "link" => $good["link"],
            ];
            Code(200, false, $data);
        } else {
            Code(403, "服务器错误，请稍后再试");
        }
    }

    public function BatchImport()
    {
        if (isset($_POST["lot_id"])) {
            $lid = $_POST["lot_id"];
            $send_id = isset($_POST["send_id"]) ? $_POST["send_id"] : 0;
            $fileName = UploadFile($_FILES["file"], $lid, "./static/upload/excel/$lid/", "xlsx");
            if (is_file("./static/upload/excel/$lid/{$fileName}")) {
                $num = $this->ImportAuction("./static/upload/excel/$lid/{$fileName}", $lid, $send_id);
                if ($num > 0) {
                    Code(200, "导入成功", "{$num}件拍品导入成功");
                } else {
                    Code(403, "禁止导入空文件");
                }
            } else {
                Code(403, "上传失败(网络原因),请稍后再试");
            }
        } else {
            Code(403, "服务器错误，请稍后再试");
        }
    }

    public function UpdateGoods()
    {
        if (isset($_POST["number"]) && isset($_POST["year"]) && isset($_POST["name"]) && isset($_POST["start"]) && isset($_POST["remark"])) {
            $number = $_POST["number"];
            // $lid = $_POST["lid"];
            $lid = 0;
            $info = [
                // "lid" => $_POST["lid"],
                "us_id" => $_POST["us_id"],
                "level" => $_POST["level"],
                "lib_number" => $_POST["lib_number"],
                "name" => $_POST["name"],
                "number" => $_POST["number"],
                "recommend" => $_POST["recommend"],
                "remark" => $_POST["remark"],
                "report" => $_POST["report"],
                "resr_price" => $_POST["resr_price"],
                "price" => $_POST["start"],
                "end_price" => $_POST["end_price"] == "" ? 0 : $_POST["end_price"],
                "begin_price" => $_POST["begin_price"] == "" ? 0 : $_POST["begin_price"],
                "size" => $_POST["size"],
                "style" => $_POST["style"],
                "summary" => $_POST["summary"],
                "year" => $_POST["year"],
                "classname" => $_POST["classname"],
                "author" => $_POST["author"],
                "appendix" => $_POST["appendix"],
                "postage" => $_POST["postage"] == "" ? 0 : $_POST["postage"],
                "location" => isset($_POST["location"]) ? $_POST["location"] : "",
                "id_number" => $_POST["id_number"],
                "indepot_date" => $_POST["indepot_date"],
                "outdepot_date" => $_POST["outdepot_date"],
                "track_number" => $_POST["track_number"],
                "is_settlement" => $_POST["is_settlement"],
                "introduction" => $_POST["introduction"],
                "keyword" => $_POST["keyword"],
                "link" => $_POST["link"],
            ];
            if (isset($_FILES["img"])) {
                $this->UploadDetailMap($_FILES["img"], $number, $lid);
            }
            if (isset($_FILES["append_img"])) {
                $this->UploadAppendMap($_FILES["append_img"], $number, $lid);
            }
            if (isset($_POST["id"])) {
                $gid = $_POST["id"];
                $good = Db::name("goods")->where("lid", $lid)->where("gid != $gid")->where("number", $number)->find();
                if (empty($good)) {
                    Db::name("goods")->where("gid", $gid)->update($info);
                    $good = Db::name("goods")->where("gid", $gid)->find();
                    $lot = Db::name("lot")->where("lid", $good["lid"])->find();
                    $img = $this->SearchImg($good["lid"], $good["number"], false, false);
                    $data = [
                        "id" => $good["gid"],
                        "eval" => $this->EvalPrice($good),
                        "lot_name" => $lot["name"],
                        "name" => $good["name"],
                        "number" => $good["number"],
                        "rate" => "",
                        "spec" => $this->Spec($good, $this->spec),
                        "start" => (float)$good["price"],
                        "year" => $good["year"],
                        "remark" => $good["remark"],
                        "imgs" => $img
                    ];
                    Code(200, "拍品信息修改成功");
                } else {
                    Code(403, "拍品号已存在");
                }
            } else {
                $good = Db::name("goods")->where("lid", $lid)->where("number", $number)->find();
                if (empty($good)) {
                    $info["lid"] = $lid;
                    $insertId = Db::name("goods")->insertGetId($info);
                    $good = Db::name("goods")->where("gid", $insertId)->find();
                    $lot = Db::name("lot")->where("lid", $good["lid"])->find();
                    $img = $this->SearchImg($good["lid"], $good["number"], false, false);
                    $data = [
                        "id" => $good["gid"],
                        "eval" => $this->EvalPrice($good),
                        "lot_name" => $lot["name"],
                        "name" => $good["name"],
                        "number" => $good["number"],
                        "rate" => "",
                        "spec" => $this->Spec($good, $this->spec),
                        "start" => (float)$good["price"],
                        "year" => $good["year"],
                        "remark" => $good["remark"],
                        "imgs" => $img
                    ];
                    Code(200, "拍品添加成功");
                } else {
                    Code(403, "拍品号已存在");
                }
            }
        } else {
            Code(403, "服务器错误，请稍后再试");
        }
    }

    public function DelGoodsImg()
    {
        if (isset($_POST["url"])) {
            $url = $_POST["url"];
            $arr = explode(Config::get("app.ip"), $url);
            $img = $arr[1];
            $brr = explode("?", $img);
            $img = $brr[0];
            if (is_file("./" . $img)) {
                unlink("./" . $img);
            }
            Code(200, "图片删除成功");
        } else {
            Code(403, "拍品号已存在");
        }
    }

    public function GetConsigns()
    {
        $aid = $this->token["id"];
        if (isset($_GET["page"]) && isset($_GET["limit"])) {
            $page = $_GET["page"];
            $limit = $_GET["limit"];
            $data = [
                "list" => [],
                "total" => 0
            ];
            if (isset($_GET["key"]) && trim($_GET["key"]) != "") {
                $good = Db::name("goods")->where("number", $_GET["key"])->find();
                if (!empty($good)) {
                    $lot = Db::name("lot")->where("is_del", 0)->where("lid", $good["lid"])->where("aid", $aid)->find();
                    if (!empty($lot)) {
                        $consign = Db::name("consigns")->where("gid", $good["gid"])->page($page, $limit)->select();
                        $data["total"] = Db::name("consigns")->where("gid", $good["gid"])->count();
                    }
                }
            } else {
                $lot = Db::name("lot")->where("is_del", 0)->where("aid", $aid)->select();
                $consign = [];
                $data["total"] = 0;
                if (!empty($lot)) {
                    $lotarr = [];
                    foreach ($lot as $value) {
                        $lotarr[] = "lid = {$value["lid"]}";
                    }
                    $lotword = join(" or ", $lotarr);
                    $consign = Db::name("consigns")->where($lotword)->page($page, $limit)->select();
                    $data["total"] = Db::name("consigns")->where($lotword)->count();
                }
            }
            if (!empty($consign)) {
                foreach ($consign as $value) {
                    $info = Db::name("goods")->where("gid", $value["gid"])->find();
                    $lot = Db::name("lot")->where("lid", $info["lid"])->find();
                    $user = Db::name("num")->where("aid", $lot["aid"])->where("ub_id", $value["ub_id"])->find();
                    $data["list"][] = [
                        "bnumer" => $user["number"],
                        "bprice" => (float)$value["price"],
                        "gname" => $info["name"],
                        "gnumber" => (int)$info["number"],
                        "id" => (int)$value["cid"],
                        "lot_name" => $lot["name"]
                    ];
                }
            }
            Code(200, false, $data);
        } else {
            Code(403, "服务器错误，请稍后再试");
        }
    }

    public function SetGoodsBreak()
    {
        if (isset($_POST["is_break"]) && isset($_POST["remark"]) && isset($_POST["id"])) {
            $gid = $_POST["id"];
            $break = $_POST["is_break"];
            $remark = $_POST["remark"];
            $info = [
                "is_break" => $break,
                "remark" => $remark
            ];
            Db::name("goods")->where("gid", $gid)->update($info);
            if ($break == 1) {
                $msg = "该拍品已设为破损";
            } else {
                $msg = "该拍品已取消破损";
            }
            Code(200, $msg);
        } else {
            Code(403, "服务器错误，请稍后再试");
        }
    }

    public function SetGoodsState()
    {
        if (isset($_POST["id"]) && isset($_POST["state"])) {
            $gid = $_POST["id"];
            $up = [
                "state" => $_POST["state"]
            ];
            if ($_POST["state"] == 5) {
                $good = Db::name("goods")->where("gid", $gid)->find();
                if ($good["is_end"] == 1) {
                    $up = [
                        "state" => 7
                    ];
                }
            } else if ($_POST["state"] == 8) {
                $up = [
                    "state" => 3
                ];
            }
            Db::name("goods")->where("gid", $gid)->update($up);
            Code(200, "拍品状态更新成功");
        } else {
            Code(403, "服务器错误，请稍后再试");
        }
    }

    public function SetGoodsStateMulti()
    {
        if (isset($_POST["ids"]) && isset($_POST["state"])) {
            $gid = explode(",", $_POST["ids"]);
            $up = [
                "state" => $_POST["state"]
            ];
            if ($_POST["state"] == 5) {
                foreach ($gid as $value) {
                    $good = Db::name("goods")->where("gid", $value)->find();
                    if ($good["is_end"] == 1) {
                        $up = [
                            "state" => 7
                        ];
                    }
                    Db::name("goods")->where("gid", $value)->update($up);
                }
            } else {
                Db::name("goods")->where([
                    "gid" => $gid
                ])->update($up);
            }
            Code(200, "拍品状态更新成功");
        } else {
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 获取成交记录Excel
    public function ExportDealGoods()
    {
        if (isset($_GET["lotId"])) {
            $lid = $_GET["lotId"];
            $goods = Db::name("goods")
                ->alias("a")
                ->join("num b", 'a.nid = b.nid', 'LEFT')
                ->join("user_buy c", 'a.ub_id = c.ub_id', 'LEFT')
                ->field("a.name as goodname, a.number as lotnum, a.final_price, b.number, c.name as username, c.tel1")
                ->where("a.lid", $lid)->where("a.state >= 3")->order("a.number asc")->select();
            if (!empty($goods)) {
                $file = $this->TransactionRecord("TransactionRecord", $goods);

                Code(200, false, $file);
            } else {
                Code(403, "暂无成交记录");
            }
        } else {
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 修改获拍号并过审
    public function passGoodsBuyNum()
    {
        $aid = isset($this->token["pid"]) ? $this->token["pid"] : $this->token["id"];
        if (isset($_POST["id"]) && isset($_POST["buy_num"]) && isset($_POST["buy_user"]) && isset($_POST["final_price"])) {
            if ($_POST["buy_num"] == "") { # 公司
                $proxy = Db::name("user_proxy")->where("name", $_POST["buy_user"])->find();
                if (empty($proxy)) {
                    Code(403, "代理公司不存在");
                } else {
                    $check_two = Db::name("user_proxy_company")->where("up_id", $proxy["up_id"])->where("aid", $aid)->find();
                    if (empty($check_two)) {
                        Code(403, "代理公司不存在");
                    } else {
                        $Upinfo = [
                            "nid" => 0,
                            "ub_id" => 0,
                            "up_id" => $proxy["up_id"],
                            "state" => 3,
                            "final_price" => $_POST['final_price'],
                        ];
                        Db::name("goods")->where("gid", $_POST["id"])->update($Upinfo);
                        Code(200, "过审成功", (object)[]);
                    }
                }
            } else { # 个人
                $check_num = Db::name("num")->where("aid", $aid)->where("number", $_POST["buy_num"])->find();
                if (empty($check_num)) {
                    Code(403, "号码牌不存在");
                } else if ($check_num["ub_id"] == 0) {
                    Code(403, "号码牌没有被绑定");
                } else {
                    $Upinfo = [
                        "nid" => $check_num["nid"],
                        "ub_id" => $check_num["ub_id"],
                        "up_id" => 0,
                        "state" => 3,
                        "final_price" => $_POST['final_price'],
                    ];
                    Db::name("goods")->where("gid", $_POST["id"])->update($Upinfo);
                    Code(200, "过审成功", (object)[]);
                }
            }
        } else {
            Code(403, "服务器错误，请稍后再试");
        }
    }

}
